import sys

from paramiko.client import SSHClient

from jobs_agency.platforms.ssh import ssh_execute
from .config import AlibabaCloudClientConfig


def make_prepare_func(acc_config: AlibabaCloudClientConfig):
    def new_prepare_func(ssh_client: SSHClient):
        print("Preparing aliyun-cli ...", file=sys.stderr)
        command = f"""
set -e
cd ~

if [ ! -f /usr/local/bin/aliyun ]; then
  echo 'installing aliyun-cli' >&2
  wget -O aliyun-cli.tgz https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
  tar xzvf ./aliyun-cli.tgz
  rm -f ./aliyun-cli.tgz
  cp ./aliyun /usr/local/bin
  rm -f ./aliyun
fi

echo 'configuring aliyun-cli' >&2
aliyun configure set \
  --profile default \
  --region {acc_config.region_id} \
  --access-key-id {acc_config.access_key_id} \
  --access-key-secret {acc_config.access_key_secret}
        """
        ssh_execute(ssh_client, command)

    return new_prepare_func


def make_release_script(instance_id: str):
    return f"""
while true; do
  echo 'Suicide (instance_id={instance_id})' >&2
  aliyun ecs DeleteInstance \
    --InstanceId {instance_id} \
    --Force true

  if [ $? -eq 0 ]; then
    echo "success" >&2
    break
  else
    echo "retry after 30s" >&2
    sleep 30
  fi 
done"""
